package first.endtoend.parse

import first.endtoend.*
import grails.validation.ValidationException

class ParseXMLBeneficiaryService
{
    Beneficiary beneficiaryInstance
    Locality localityInstance
    Address addressInstance
    Family familyInstance
    FairPricesShop shopInstance

    def parseMethod(String filePath)
    {
        def rootElement = new XmlParser().parse(filePath)
        Category categoryInstance
        def bens = new ArrayList<Family>()
        Beneficiary ben1

        def benefs = rootElement.children()
        for (int i = 0; i < benefs.size(); i++)
        {
            def benefElement = benefs.get(i)
            categoryInstance = Category.findByName(benefElement.category.text())
            if (categoryInstance)
            {

                //create an adress like specified in csv file, see standard related to the structure of this file
                String adresss = (String) benefElement.address.text()
                String lastName = (String) benefElement.lastName.text()
                String telephone = (String) benefElement.telephone.text()
                String firstName = (String) benefElement.firstName.text()
                String photoURL = (String) benefElement.photoURL.text()
                String tataId = (String) benefElement.tataId.text()
                String shopName = (String) benefElement.shop.text()
                println("HEYYY" + adresss)
                println("TATA ID" + tataId)
                addressInstance = new Address(adresss)
                if (!addressInstance.validate())
                {
                    throw new ValidationException("addressInstance is not valid", addressInstance.errors)
                }

                shopInstance = FairPricesShop.findByFpsName(shopName)
                //TODO add control to see if family exist -> update this family
                //TODO make the id auto incremented!!!

                Family aFamily = Family.findByFamilyNameAndTelephone(lastName, telephone)
                if (bens.size() == 0)
                {
                    familyInstance = new Family(familyName: lastName, category: categoryInstance, address: addressInstance, telephone: telephone)

                } else
                {
                    bens.each {
                        if (it.familyName.equals(lastName) && it.telephone.equals(telephone))
                        {
                            familyInstance = it
                        } else
                        {
                            familyInstance = new Family(familyName: lastName, category: categoryInstance, address: addressInstance, telephone: telephone)
                        }
                    }
                }

                if (aFamily)
                {
                    println("family will be updated")
                    aFamily.setCategory(categoryInstance)
                    aFamily.setAddress(addressInstance)
                    if (shopInstance)
                    {
                        aFamily.setFps(shopInstance)
                    } else
                    {
                        println("this shop does not exist")
                    }

                    Beneficiary existantBenef = Beneficiary.findByFamilyAndFirstNameAndLastName(aFamily, firstName, lastName)
                    if (existantBenef)
                    {
                        println("IN EXISTANT BENEF")
                        existantBenef.setPhotoURL(photoURL)
                        existantBenef.setTataId(tataId)
                        existantBenef.save()
                    } else
                    {
                        println("IN NEW BENEF")
                        Beneficiary ben = new Beneficiary()
                        ben.firstName = firstName
                        ben.lastName = lastName
                        ben.family = aFamily
                        ben.photoURL = photoURL
                        ben.tataId = tataId
                        ben.save()
                        if (aFamily.beneficiaries == null)
                        {
                            aFamily.beneficiaries = new ArrayList<Beneficiary>()
                        }
                        aFamily.beneficiaries.add(ben)
                    }
                    aFamily.save()

                } else
                {
                    if (!familyInstance.validate())
                    {
                        throw new ValidationException("Family is not valid", familyInstance.errors)
                    } else
                    {
                        //nothing
                    }

                    ben1 = new Beneficiary()
                    ben1.setFirstName(firstName)
                    ben1.setLastName(lastName)
                    ben1.setFamily(familyInstance)
                    ben1.setPhotoURL(photoURL)
                    ben1.setTataId(tataId)

                    if (familyInstance.beneficiaries == null)
                    {
                        familyInstance.beneficiaries = new ArrayList<Beneficiary>()
                    }


                    familyInstance.beneficiaries.add(ben1)
                    if (shopInstance)
                    {
                        familyInstance.setFps(shopInstance)
                    } else
                    {
                        println("this shop does not exist")
                    }
                    if (!ben1.validate())
                    {
                        throw new ValidationException("Beneficiary is not valid", ben1.errors)
                    }

                    if (ben1.hasErrors())
                        println ben1.errors


                }

                bens.add(familyInstance)

            } else
            {
                println("Category doesn't exist")
            }
        }


        bens
    }
}
